<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="年月" prop="planMonth">
        <el-date-picker clearable
                        v-model="queryParams.planMonth"
                        type="month"
                        value-format="yyyy-MM"
                        placeholder="选择排产月份">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="产地" prop="factoryId">
        <el-select v-model="queryParams.factoryId" placeholder="请选择" filterable clearable @change="factoryChange">
          <el-option v-for="team in factoryList" :key="team.deptId" :label="team.deptName" :value="team.deptId" />
        </el-select>
      </el-form-item>
      <el-form-item label="班组" prop="teamId">
        <el-select v-model="queryParams.teamId" placeholder="请选择" filterable clearable>
          <el-option v-for="team in teamList" :key="team.deptId" :label="team.deptName" :value="team.deptId" />
        </el-select>
      </el-form-item>
      <el-form-item label="订单合同号" prop="contractCode">
        <el-input v-model="queryParams.contractCode" placeholder="请输入订单合同号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="产品编码" prop="bomCode">
        <el-input v-model="queryParams.bomCode" placeholder="请输入产品编码" />
      </el-form-item>
      <el-form-item label="产品名称" prop="bomName">
        <el-input v-model="queryParams.bomName" placeholder="请输入产品名称" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

<!--    <el-row :gutter="10" class="mb8">-->
<!--      <el-col :span="1.5">-->
<!--        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="teamSelect" @click="handlePlan('MULITPLE', {})"-->
<!--          v-hasPermi="['factory:factorymplan:edit']">执行排产（当前选择)</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="teamSelect" @click="handlePlanOfAll('ALL')"-->
<!--                   v-hasPermi="['factory:factorymplan:edit']">执行排产（符合条件）</el-button>-->
<!--      </el-col>-->
<!--      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>-->
<!--    </el-row>-->

    <el-table v-loading="loading"
              ref="multipleTable"
              border style="width:100%;"
              :data="factoryWorkOrderList">
<!--      <el-table-column type="selection" width="55" align="center" :selectable="handleDisable" />-->
      <el-table-column label="排产年月" align="center" prop="planMonth" width="120"/>
      <el-table-column label="班组名称" align="center" prop="teamName"  width="150"/>
      <el-table-column label="订单合同号" align="center" prop="contractCode" />
      <el-table-column label="产品编码" align="center" prop="bomCode" />
      <el-table-column label="产品名称" align="center" prop="bomName" />
      <el-table-column label="规格型号" align="center" prop="productStandard" />
<!--      <el-table-column label="产品单位" align="center" prop="productUnit" />-->
<!--      <el-table-column label="产品数量" align="center" prop="workerOrdernum" />-->
      <el-table-column label="生产状态" align="center" prop="workerOrderstatusDesc" />
      <el-table-column label="排产数量" align="center" prop="planCapacity" />
<!--      <el-table-column label="采样数量" align="center" prop="sampleNum" />-->
      <!--<el-table-column label="排产说明" align="center" prop="planDesc" />
      <el-table-column label="分厂名称" align="center" prop="factoryName" />-->
<!--      <el-table-column label="总部开始时间" align="center" prop="planStartdate" width="100"/>-->
<!--      <el-table-column label="总部完成时间" align="center" prop="planFinishdate" width="100"/>-->
      <el-table-column label="排产开始日期" align="center" prop="mplanStartDate" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.mplanStartDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="排产完成时间" align="center" prop="mplanEndDate" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.mplanEndDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否缺料" align="center" prop="missingMaterial"  width="80px"/>
     <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" v-if="scope.row.mplanStatus == '0'"
            @click="handlePlan(scope.row)" v-hasPermi="['factory:factorymplan:edit']">执行排产</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" v-if="scope.row.mplanStatus == '1'"
            @click="handlePrint(scope.row)" v-hasPermi="['factory:factorymplan:edit']">打印工单</el-button>
        </template>
      </el-table-column>-->
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改订单信息对话框 -->
    <el-dialog title="分厂月排产" :visible.sync="open" width="1400px" append-to-body :close-on-click-modal ="false">
      <!-- 数据统计 -->
      <div style="clear: both;margin-bottom: 30px;">
        <el-row :gutter="26">
          <el-col :span="3">
            <div>
              <el-statistic title="所选班组">
                <template slot="formatter">{{ teamName }}</template>
              </el-statistic>
            </div>
          </el-col>
          <el-col :span="3">
            <div>
              <el-statistic title="已选数量">
                <template slot="formatter">{{selectedCount}}条</template>
              </el-statistic>
            </div>
          </el-col>
          <el-col :span="3">
            <div>
              <el-statistic group-separator="," :precision="2" :value="standardCapacity" title="标准产能/天"/>
            </div>
          </el-col>
          <el-col :span="3">
            <div>
              <el-statistic group-separator="," :precision="2" :value="totalStandardCapacity" title="总标准产能" />
            </div>
          </el-col>
          <!--<el-col :span="3">
            <div>
              <el-statistic title="剩余天数(本月)">
                <template  slot="formatter">{{restDays}}天</template>
              </el-statistic>
            </div>
          </el-col>-->
          <el-col :span="3">
            <div>
              <el-statistic group-separator="," :precision="2" :value="restCapacity" title="总剩余产能"/>
            </div>
          </el-col>
          <el-col :span="3">
            <div>
              <el-statistic group-separator="," :precision="2" :value="needCapacity" title="所需产能"/>
            </div>
          </el-col>
        </el-row>
      </div>

      <div style="float: right; clear: both;">
        <el-form ref="form" :model="form" :rules="rules" label-width="80px" style="margin-bottom: 10px">
          <el-date-picker clearable
            v-model="form.planMonth"
            type="month"
            value-format="yyyy-MM"
            placeholder="选择排产月份">
          </el-date-picker>
          <!--<el-checkbox v-model="form.chooseMonth">下月</el-checkbox>-->
          <el-button type="primary" @click="excutePlan" style="margin-left: 20px;">排产计算</el-button>
        </el-form>
      </div>

      <template v-for="planItem in mplanProductVOList">
        <div style="margin-top: 20px;clear: both;">
          <el-tag :type="planItem.typeTag" size="medium"  effect="light">
            产品信息：{{planItem.productCode}} {{planItem.productName}}
          </el-tag>
        </div>
        <el-table
          style="width: 100%"
          row-key="id"
          border
          lazy
          v-loading="loading2"
          :load="load"
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
          :data="planItem.mplanList">
          <el-table-column label="子项物料编码" align="center" prop="bomCode" />
          <el-table-column label="物料名称" align="center" prop="bomName" />
          <el-table-column label="订单合同号" align="center" prop="contractCode" />
          <el-table-column label="规格型号" align="center" prop="productStandard" />
          <el-table-column label="分单数量" align="center" prop="workerOrdernum" />
          <el-table-column label="采样数量" align="center" prop="sampleNum" />
          <el-table-column label="库存" align="center" prop="storeNum" width="90px"/>
          <el-table-column label="排产数量" align="center" prop="planNum" width="110px">
            <template slot-scope="scope">
              <el-tag type="success" v-if="scope.row.planNum!=null">{{scope.row.planNum}} {{scope.row.bomUnit == null ? '' : scope.row.bomUnit}}</el-tag>
            </template>
          </el-table-column>
          <!--<el-table-column label="分厂名称" align="center" prop="factoryName" />-->
          <el-table-column label="班组名称" align="center" prop="teamName" />
          <!--<el-table-column label="库存情况" align="center" prop="inventoryDesc" />-->
          <el-table-column label="排产开始时间" align="center" prop="mplanStartDate" width="100"/>
          <el-table-column label="排产完成时间" align="center" prop="mplanEndDate" width="100">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.mplanEndDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="产能情况" align="center" prop="capacityDesc" />
          <el-table-column label="总部开始时间" align="center" prop="planStartdate" width="100"/>
          <el-table-column label="总部完成时间" align="center" prop="planFinishdate" width="100"/>
          <!--<el-table-column label="是否满足" align="center" prop="capacityDesc"/> -->
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handPlanRemoveOrder(scope.row)"
                         v-hasPermi="['factory:factorymplan:edit']">移除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <div slot="footer" class="dialog-footer" style="text-align: center;">
        <el-button  type="primary" @click="submitPlan">提交排产</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMFactoryWorkorder, listFactoryMplanWorkorder, listFactoryMplanWorkorderOfAll, getWorkorder, updateWorkorder } from "@/api/sm/order/workorder";
import { printMplanWorkOrder, listFactorymplan, excuteFactoryMPlan, submitFactoryMPlan,planviewlist_month } from "@/api/sm/factory/factorymplan";
import { listTeam,listFactory } from "@/api/system/dept";
import { listChildren } from "@/api/sm/basic/bominfo";

export default {
  name: "Orderinfo",
  dicts: ['order_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      loading2: false,
      calShow: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,

      teamSelect: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      plantotal: 0,
      //分厂待排产订单信息表格数据
      factoryWorkOrderList: [],
      //排产工单,排产计算得到的结果
      mplanProductVOList: [],
      //排产结果
      planResultList: [],
      factoryList: [],
      teamList: [],
      planStatusList: [
        {
          "label": "待排产",
          "value": 0
        }
        ,
        {
          "label": "排产完成",
          "value": 1
        }
      ],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 同步时间时间范围
      daterangeOrderDate: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 50,
        teamId: null,
        bomCode: null,
        bomName: null,
        mplanStatus: 0,
        workerConfirmstatus: 1,
        workerOrdertype: 1,
        excludeIds: [],
        planMonth: null,
      },
      // 表单参数
      form: {
        teamId: null,
        planMonth: null,
        chooseMonth: null,
        workOrderIds: null
      },
      // 表单参数
      form1: {
        planMonth: null,
        mplanList: null
      },
      // 表单校验
      rules: {
      },
      // 统计数据
      teamName: "导管鞘组",
      selectedCount: 18,
      standardCapacity: 20000,
      restDays: 20,
      totalStandardCapacity: 60000,
      restCapacity: 3000,
      needCapacity: 5000,
      action: null,
    };
  },
  created() {
    this.init();
    this.getList();
    this.getFactoryList();
  },
  methods: {
    init() {
      const currentDate = new Date();
      const year = currentDate.getFullYear();
      const month = (currentDate.getMonth() + 1).toString().padStart(2, '0'); // 月份需要加1，然后确保是两位数
      const day = currentDate.getDate().toString().padStart(2, '0'); // 获取日并确保是两位数
      this.queryParams.planMonth = `${year}-${month}`;
    },
    load(tree, treeNode, resolve) {
      console.log(tree);
      let data = {
        "parentBomCode": tree.bomCode,
        "productId": tree.productId,
        "orderCode": tree.orderCode,
        "customName": tree.customName,
        "sampleNum": tree.sampleNum ? tree.sampleNum : 0,
        "workerOrdernum": tree.workerOrdernum ? tree.workerOrdernum : 0,
        // "semiProductPlanNum": tree.semiProductPlanNum ? tree.semiProductPlanNum : tree.planNum
      };
      listChildren(data).then((res) => {   //getChildMenu是我们自己的调用后台的封装
        resolve(                            //resolve是组件的
          res.data  //根据自己的格式,将查到的子菜单数组填充
        )
      })
    },
    handleDisable(row, index) {
      if (row.mplanStatus == '1') {
        return false
      } else {
        return true
      }
    },
    /** 查询订单信息列表 */
    getFactoryList() {
      this.loading = true;
      listFactory({"level":2}).then(response => {
        this.factoryList = response.data;
        // this.queryParams.factoryId = this.factoryList[0].deptId;
        this.getTeamList(this.queryParams.factoryId);
        this.loading = false;
      });
    },
    factoryChange(){
      this.getTeamList(this.queryParams.factoryId);
    },
    /** 查询订单信息列表 */
    getTeamList(parentId) {
      this.loading = true;
      listTeam({"parentId":parentId}).then(response => {
        this.teamList = response.data;
        this.loading = false;
      });
    },

    /** 查询订单信息列表 */
    getList() {
      this.loading = true;
      planviewlist_month(this.queryParams).then(response => {
        this.factoryWorkOrderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        planChooseMonth: null,
        workOrderIds: null
      };
      this.resetForm("form");
    },
    reset1() {
      this.form1 = {
        planMonth: null,
        mplanList: null
      };
      this.resetForm("form1");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.excludeIds = [];
      this.queryParams.pageNum = 1;
      if(this.queryParams.teamId!=null && this.queryParams.teamId!=undefined){
        this.teamSelect = false;
      }
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeOrderDate = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    handlePrint(row) {
      this.loading = true;
      const ids = row.id || this.ids;
      printMplanWorkOrder(ids).then(response => {
        let blob = new Blob([response], { type: "application/vnd.ms-excel" });
        var downloadElement = document.createElement("a");

        var href = window.URL.createObjectURL(blob); //创建下载的链接

        downloadElement.href = href;

        downloadElement.download = '月排产_工单'; //下载后文件名

        document.body.appendChild(downloadElement);

        downloadElement.click(); //点击下载

        document.body.removeChild(downloadElement); //下载完成移除元素

        window.URL.revokeObjectURL(href); //释放掉blob对象

        this.loading = false;
      });
    },
    /** 执行排产操作 */
    handlePlan(action, row) {
      this.action = action;
      this.reset1();
      this.loading2 = true;
      const ids = row.id || this.ids;
      if(ids==null || ids==''){
        this.loading2 = false;
        return;
      }

      this.orderplanList = null;
      listFactoryMplanWorkorder({ "ids": ids + '',"teamId":this.queryParams.teamId }).then(response => {
        this.mplanProductVOList = response.data.mplanProductVOList || [];
        this.open = true;
        this.selectedCount = this.ids.length;
        this.standardCapacity = new Number(response.data.standardCapacity);
        this.totalStandardCapacity = new Number(response.data.totalStandardCapacity);
        this.restCapacity = new Number(response.data.nextCapacity);
        this.needCapacity = new Number(response.data.needCapacity);
        this.restDays = response.data.restDays;
        this.teamName = response.data.teamName;
        this.calShow=false;
        this.loading2 = false;
      });
    },
    handlePlanOfAll(action) {
      this.action = action;
      if (this.action === 'ALL') {
        this.queryParams.excludeIds = [];
      }
      this.reset1();
      this.loading2 = true;
      this.orderplanList = null;
      listFactoryMplanWorkorderOfAll(this.queryParams).then(response => {
        this.mplanProductVOList = response.data.mplanProductVOList || [];
        this.open = true;
        this.calShow=false;
        this.loading2 = false;
      });
    },

    handPlanRemoveOrder(row) {
      const id = row.id
      this.mplanProductVOList.map((item, index) => {
        item.mplanList.map((_item, _index) => {
          if (_item.id == id) {
            item.mplanList.splice(index, 1);//index 当前元素索引；1：需要删除的元素个数
            this.queryParams.excludeIds.push(id);
          }
        });
        // 判断一个半成品也没有了
        if (item.mplanList.length === 0) {
          this.mplanProductVOList.splice(index, 1);
        }
      });

      if (this.mplanProductVOList.length === 0) {
        this.$modal.msgSuccess("仅有一个产品都被删除了，分厂月排产窗口被关闭");
        this.open = false;
        this.queryParams.excludeIds = [];
        return;
      }
      if (this.action === 'MULTIPLE') {
        // 重新计算开始
        for (let i = 0; i < this.factoryWorkOrderList.length; i++) {
          let cur = this.factoryWorkOrderList[i];
          if (cur.id === row.id) {
            this.$refs.multipleTable.toggleRowSelection(this.factoryWorkOrderList[i], false);
            break;
          }
        }
        // 计算后的数据，如果存在也要移除
        for (let i = 0; i < this.ids.length; i++) {
          if (this.ids[i] === id) {
            this.ids.splice(i, 1);
            break;
          }
        }
        // 重新做排产计算
        this.handlePlan(this.action,{});
      } else {
        this.handlePlanOfAll('ALL_DELETE');
      }
    },

    getCurrentDate() {
      const now = new Date();
      const year = now.getFullYear();
      const month = now.getMonth() + 1; // 月份是从0开始的，所以需要加1
      return `${year}-${month.toString().padStart(2, '0')}`;
    },

    excutePlan() {
      if (this.mplanProductVOList.length == 0) {
        alert("无排产工单");
        return;
      }

      if(this.form.planMonth==null || this.form.planMonth==undefined){
        alert("请选择排产月份");
        return;
      }

      let currentDate=this.getCurrentDate();
      if(this.form.planMonth<currentDate){
        alert("排产月份不能小于当前月份");
        return;
      }

      this.loading2 = true;
      let planWorkOrderList = [];
      for(let obj of this.mplanProductVOList) {
        for(let _obj of obj.mplanList) {
          planWorkOrderList.push(_obj);
        }
      }
      this.form.teamId = this.queryParams.teamId;
      this.form.workOrderIds = planWorkOrderList.map(item => item.id).join(',');
      excuteFactoryMPlan(this.form).then(response => {
        this.mplanProductVOList = response.data.mplanProductVOList || [];
        this.teamName = response.data.teamName;
        this.selectedCount = this.ids.length;
        this.standardCapacity = new Number(response.data.standardCapacity);
        this.totalStandardCapacity = new Number(response.data.totalStandardCapacity);
        this.restCapacity = new Number(response.data.nextCapacity);
        this.needCapacity = new Number(response.data.needCapacity);
        this.restDays = response.data.restDays;
        this.calShow=true;
        this.$modal.msgSuccess("排产成功");
        this.loading2 = false;
      });
    },

    submitPlan() {
      if(this.calShow==false){
        alert("请先月排产,再提交");
        return;
      }

      if (this.mplanProductVOList.length == 0) {
        alert("无排产详情");
        return;
      }
      let planWorkOrderList = [];
      for(let obj of this.mplanProductVOList) {
        for(let _obj of obj.mplanList) {
          planWorkOrderList.push(_obj);
        }
      }
      this.form1.planMonth=this.form.planMonth;
      this.form1.mplanList = planWorkOrderList;
      submitFactoryMPlan(this.form1).then(response => {
        this.$modal.msgSuccess("排产提交成功");
        this.open = false;
        this.getList();
      });
    },
  }
};
</script>
